<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>坐标轴</title>
  <style>
  </style>
</head>
<body>
<canvas id="canvas" width="500" height="500"></canvas>
<script >

  const canvas = document.getElementById('canvas')
  const ctx = canvas.getContext('2d')

  drawGrid(ctx, 'lightgray', 20, 20)
  drawAxis(ctx)
  drawAxisTicks(ctx, 20)
  // 画网格
  function  drawGrid(context, color, stepX, stepY) {
    context.strokeStyle = 'lightgray';
    context.lineWidth = 0.5;
    for (let i = stepX + 0.5; i < context.canvas.width; i += stepX) {
      context.beginPath()
      context.moveTo(i, 0)
      context.lineTo(i, context.canvas.height)
      context.stroke()
  }
    for (let i = stepY + 0.5; i < context.canvas.height; i += stepY){
      context.beginPath()
      context.moveTo(0, i)
      context.lineTo(context.canvas.width, i)
      context.stroke()
    }
  }
  // 画坐标轴
  function drawAxis(context) {
    context.save()
    context.strokeStyle = 'red'
    context.lineWidth = 2
    context.beginPath()
    context.moveTo(0, 0)
    context.lineTo(0, context.canvas.height)
    context.lineTo(context.canvas.width, context.canvas.height)
    context.stroke()
    context.restore()
  }
  // 画x轴刻度
  function drawAxisTicks(context, stepX) {
    context.strokeStyle = 'red'
    context.lineWidth = 2
    for (let i = stepX + 0.5; i < canvas.width; i += stepX) {
      context.beginPath()
      context.moveTo(i, canvas.height-stepX+10)
      context.lineTo(i, canvas.height)
      context.stroke()
    }
    // 画y轴刻度
    for (let i = stepX + 0.5; i < canvas.height; i += stepX) {
      context.beginPath()
      context.moveTo(0, i)
      context.lineTo(stepX-10, i)
      context.stroke()
    }
}
</script>
</body>
</html>